package it.saga.pes.frontoffice.servizi.struts2.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.opensymphony.xwork2.conversion.TypeConversionException;

public class StringToDateConverter extends StrutsTypeConverter {

	private static final DateFormat DATET_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
	
	@Override
	public Object convertFromString(Map context, String[] strings, Class toClass) {
		if (strings == null || strings.length == 0 || strings[0].trim().length() == 0) {
			return null;
		}
		try {
			return DATET_FORMAT.parse(strings[0]);
		} catch (ParseException e) {
			//return null;
			throw new TypeConversionException(e);
		}
	}
	
	@Override
	public String convertToString(Map context, Object date) {
		if (date != null && date instanceof Date) {
			return DATET_FORMAT.format(date);
		} else {
			return "";
		}
	}
}
